package com.healthmgmt.app.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.healthmgmt.common.constant.Constants;
import com.healthmgmt.common.core.domain.AjaxResult;
import com.healthmgmt.common.core.domain.model.LoginBody;
import com.healthmgmt.common.core.redis.RedisCache;
import com.healthmgmt.common.service.SmsService;
import com.healthmgmt.framework.web.service.SysLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.healthmgmt.common.constant.CacheConstants.SMS_CODE_KEY;
import static com.healthmgmt.common.constant.UserConstants.USER_TYPE_MEMBER;

@RestController
@RequestMapping("/app")
public class AppLoginController {
    @Autowired
    private SysLoginService loginService;

    @Resource
    private SmsService smsService;

    @Resource
    private RedisCache redisCache;

    /**
     * 获取验证码
     *
     * @param phone 手机号
     * @return 结果
     */
    @PostMapping("/sms/{phone}")
    public AjaxResult sms(@PathVariable("phone") String phone)
    {
        Assert.notNull(phone, "手机号不能为空");
        Assert.isTrue(PhoneUtil.isPhone(phone), "手机号不正确");
        Map<String, String> params = new HashMap<>();
        String code = RandomUtil.randomNumbers(6);
        params.put("code", code);
        boolean success = smsService.sendSms(phone, params);
        System.out.println("success:" + success);
        if (success) {
            redisCache.setCacheObject(SMS_CODE_KEY + phone, code, 5, TimeUnit.MINUTES);
        }
        return AjaxResult.success(code);
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        if (loginBody.getType().equals(USER_TYPE_MEMBER)) {
            Assert.notEmpty(loginBody.getCode(), "验证码不能为空");
            String code = redisCache.getCacheObject(SMS_CODE_KEY + loginBody.getUsername());
            Assert.notEmpty(code, "验证码已过期");
            Assert.equals(code, loginBody.getCode(), "验证码不正确");
            redisCache.deleteObject(SMS_CODE_KEY + loginBody.getUsername());
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.appLogin(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
